using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Collections;

namespace Test.Sockets
{
    /// <summary>
    /// 
    /// </summary>
    internal class SocketUtil
    {
        /// <summary>
        /// Reads the message from <paramref name="socket">socket</paramref>.
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        internal static String GetReturnedMessage(Socket socket)
        {
            if (null == socket)
                throw new ArgumentNullException("socket");
            
            // [!] Will be zero if Receive has not yet been called.
            //if (socket.Available == 0)
            //    return String.Empty;
            //socket.Poll(500, SelectMode.SelectRead);

            //IList read = new List<Socket>();
            //read.Add(socket);

            //Socket.Select(read, null, null, -1); 

            using (StringWriter writer = new StringWriter())
            {
                Int32 bytesRead = 0;

                Byte[] buffer = new Byte[1024];

                try
                {
                    if (false == socket.Connected)
                        throw new InvalidOperationException("Socket not connected.");

                    // [!] Once zero bytes have been received, 
                    //     the socket has been closed by the peer.
                    while ((bytesRead = socket.Receive(buffer)) > 0)
                    {
                        writer.Write(Encoding.ASCII.GetString(buffer, 0, bytesRead));
                    }

                    // socket.Disconnect(true);  // NOPE 

                    return writer.GetStringBuilder().ToString();
                }
                catch (SocketException e)
                {
                    if (false == socket.Connected)
                    {
                        Console.WriteLine("Socket has been disconnected!");
                    }

                    Console.WriteLine("{0}, {1}, {2}",
                        e.StackTrace,
                        e.ErrorCode,
                        socket.Connected
                    );

                    throw;
                }

                return null;
            }
        }
    }
}
